import { useEffect, useMemo, useState, useCallback } from "react";
import TextAear from "@/componets/textAear";
import {
  Container,
  LeftContent,
  RightContent,
  ExpendBtn,
  Result,
  Dragger,
  ActionItem,
  ResultList,
  ResultItem,
} from "./styled";
import { useMouse } from "@/utils/useMouse";
import moment from "moment";
import { message } from "antd";
import { usePresskeyborad } from "@/utils/usePress";
import MarkDownComponent from "../markdown";
import { CheckboxValueType } from "antd/es/checkbox/Group";

interface resultType {
  createTime: string;
  result: string;
}

interface Props {
  _id: number;
  description: string;
  handleChange: (text: string | CheckboxValueType[]) => void;
  codeVal: string;
}

const JsBox = ({ description, codeVal, handleChange, _id }: Props) => {
  const { keys } = usePresskeyborad();
  const isCtrS = useMemo(
    () => keys.includes("Control") && keys.includes("s"),
    [keys]
  );
  const [width, setWidth] = useState(250);
  const [height, setHeight] = useState(275);
  const [isPress, setIsPress] = useState(false);
  const [startY, setStartY] = useState(-1);
  const [endY, setEndY] = useState(275);
  const { y } = useMouse();
  const [results, setResults] = useState<resultType[]>([]);

  // useEffect(() => {
  //   if (sessionStorage.getItem("practice-code" + _id)) {
  //     handleChange(String(sessionStorage.getItem("practice-code" + _id)));
  //   }
  // }, []);

  useEffect(() => {
    isCtrS && saveHandle();
  }, [isCtrS]);

  const mouseDownHandle = (e: any) => {
    const { clientY } = e;
    setStartY(clientY);
    setIsPress(true);
  };

  useEffect(() => {
    if (isPress && startY != -1) {
      setHeight(endY + startY - y);
    }
  }, [height, y, isPress, startY]);

  const mouseUpHandle = (e: any) => {
    setIsPress(false);
    setStartY(-1);
    setEndY(height);
  };
  const saveHandle = () => {
    sessionStorage.setItem("practice-code" + _id, codeVal);
    message.success("保存成功");
  };
  const runHandle = () => {
    if (!codeVal) return;
    let createTime = moment(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss");
    console.print = console.log;
    console.print = function (value: string) {
      return value;
    };
    console.print(codeVal);
    const result = eval(codeVal);
    const newResult = JSON.parse(JSON.stringify(results));
    newResult.push({
      createTime,
      result: JSON.stringify(result),
    });
    setResults(newResult);
  };
  return (
    <>
      <Container onMouseUp={mouseUpHandle}>
        <LeftContent width={width}>
          {description ? (
            <MarkDownComponent
              style={{ color: "#dbdbdb" }}
              text={description}
            />
          ) : (
            <div style={{ color: "#fff", textAlign: "center" }}>暂无描述</div>
          )}
        </LeftContent>
        <ExpendBtn onClick={() => setWidth(width == 0 ? 250 : 0)} width={width}>
          &gt;
        </ExpendBtn>
        <RightContent>
          <TextAear
            height={height}
            onChange={handleChange}
            codeVal={codeVal ?? ""}
          />
          <Result height={height}>
            <Dragger onMouseDown={mouseDownHandle}>
              <ActionItem onClick={saveHandle}>保存(ctr+s)</ActionItem>
              <ActionItem onClick={runHandle}>运行</ActionItem>
              <ActionItem onClick={() => setResults([])}>清空</ActionItem>
            </Dragger>
            <ResultList height={height}>
              {results.map((item, index) => (
                <ResultItem key={index}>
                  {item.createTime} : {item.result}
                </ResultItem>
              ))}
            </ResultList>
          </Result>
        </RightContent>
      </Container>
      <div style={{ fontSize: "14px", color: "#888" }}>ps: 该程序输出为console.print</div>
    </>
  );
};

export default JsBox;
